﻿using System;
using System.Linq;

namespace DNUtil
{
    public static class TypeUtil
    {
        /// <summary>
        /// Returns true if the specified type represents a nullable or reference type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsNullable(this Type type)
        {
            if (type.IsValueType == false) return true; // ref-type
            if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
            
            return false; // value-type
        }

        /// <summary>
        /// Returns a type representing a Nullable of the specified type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Type GetNullableType(this Type type)
        {
            if (IsNullable(type) == false)
            {
                Type nullable = typeof(Nullable<>);
                return nullable.MakeGenericType(new[] { type });
            }
            return type;
        }
    }
}
